import tkinter as tk
from tkinter import ttk
import subprocess

import win32print


def get_windows_default_printer():
    try:
        import win32print
        default_printer = win32print.GetDefaultPrinter()
        return default_printer
    except ImportError:
        return ""

def get_windows_printer_list():
    """获取Windows系统打印机列表"""
    printers = []

    try:
        # 尝试使用pywin32获取打印机列表（更可靠的方法）
        import win32print
        printer_names = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS)
        printers = [printer[2] for printer in printer_names]
    except ImportError:
        # 如果pywin32不可用，使用PowerShell命令获取打印机列表
        try:
            cmd = ['powershell', '-command', 'Get-Printer | Select-Object -ExpandProperty Name']
            result = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=10)
            if result.returncode == 0:
                printers = [line.strip() for line in result.stdout.split('\n') if line.strip()]
        except (subprocess.SubprocessError, subprocess.TimeoutExpired):
            printers = ["无法获取打印机列表 - 请安装pywin32模块"]

    return printers if printers else ["未找到打印机"]


class PrinterDialog:
    def __init__(self, master, fields,defvalues):
        self.master = master
        self.fields = fields
        self.values = defvalues
        self.entries = {}
        self.results = None
        self.width = 320
        self.height = 160
        self.results = None
        self.setup_ui()
        screen_width = self.master.winfo_screenwidth()
        screen_height = self.master.winfo_screenheight()
        x = int((screen_width / 2) - (self.width / 2))
        y = int((screen_height / 2) - (self.height / 2))
        self.master.geometry(f'{self.width}x{self.height}+{x}+{y}')


    def setup_ui(self):
        self.master.title("打印参数设置")

        # 创建输入框和标签
        for i, field in enumerate(self.fields):
            label = ttk.Label(self.master, text=field + ":")
            label.grid(row=i, column=0, padx=5, pady=5, sticky="e")
            entry = ttk.Entry(self.master)
            entry.delete(0, tk.END)
            entry.insert(0, self.values[i])
            self.entries[field] = entry

            if i == 0:
                self.combobox = ttk.Combobox(self.master)    # 打印机清单
                printers = get_windows_printer_list()
                defprinter = get_windows_default_printer()
                self.combobox['values'] = printers
                self.combobox.set(defprinter)
                self.combobox.grid(row=i, column=1, padx=5, pady=5, sticky="e")
            else:
                entry.grid(row=i, column=1, padx=5, pady=5, sticky="we")

        # 创建按钮
        button_frame = ttk.Frame(self.master)
        button_frame.grid(row=len(self.fields), column=0, columnspan=2, pady=10)

        ttk.Button(button_frame, text="确定", command=self.on_ok).pack(side="left", padx=5)
        ttk.Button(button_frame, text="取消", command=self.on_cancel).pack(side="left", padx=5)

    def on_ok(self):
        self.entries[self.fields[0]].delete(0, tk.END)
        self.entries[self.fields[0]].insert(0, self.combobox.get())
        self.results = {field: entry.get() for field, entry in self.entries.items()}
        self.master.destroy()

    def on_cancel(self):
        self.results = None
        self.master.destroy()

    def show(self):
        self.master.wait_window()
        return self.results
